import React,  { Fragment ,useRef } from "react";
import {Button, Form, Icon, message, Modal, Progress, Upload} from "antd";
import service from "../../libs/request";
import {diffProps} from "../../libs/funcs";

class FormSignName extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            disabled: false,
            data:{},
            chunkSize:1024 * 1024 * 5, //切片的大小
            currentTrunk:0, //当前上传分片的索引
            percent:0,
            fileList: this.handleInitialValue(),
            is_show_process:false,
            previewVisible:false,
            previewImage: '',
        };

    }


    handleInitialValue = () => {
        try {
            if (Array.isArray(this.props.initialValue) && this.props.initialValue.length > 0 && this.props.initialValue[0].hasOwnProperty("url")){
                return this.props.initialValue;
            }

            return [];
        }catch (e) {
            return [];
        }
    };

    // 上传失败
    uploadError = () => {
        let data = {
            uid: (this.state.fileList.length + 1).toString,
            name: this.state.data["name"],
            status: 'error',
            url: "",
            thumbUrl: "",
        };
        this.setState({
            disabled: false,
            is_show_process:false,
            fileList: [...this.state.fileList,data]
        });
        message.error("上传失败")
    };

    // 上传成功
    uploadSuccess = (info) => {
        let data = {
            uid: info["unique_id"],
            name: info["fileName"],
            status: 'done',
            url: info["url"],
            thumbUrl: info["thump_url"],
        };
        let that = this;
        this.setState({
            disabled: false,
            is_show_process:false,
            fileList: this.props.single ? [data] : [...this.state.fileList,data],
            percent:100
        },function () {
            let obj = {};
            obj[that.props.field ? that.props.field : "default_upload_file"] = JSON.stringify(that.state.fileList);
            this.props.form.setFieldsValue(obj);
        });


    };

    sendFile = () => {
        console.log("当前分片",this.state.currentTrunk)
        let start = this.state.currentTrunk * this.state.chunkSize;

        let end = 0;
        if(this.state.currentTrunk+1 === this.state.data.chunkNum){
            end = this.state.data.len
        }else {
            end = start + this.state.chunkSize;
        }
        let blob = this.state.data.file.slice(start,end);
        let formData = new FormData();
        formData.append('file', blob);
        formData.append('fileName', this.state.data.name);
        formData.append('size', this.state.data.len);
        formData.append('type', this.state.data.type);
        formData.append('chunkNum', this.state.data.chunkNum);
        formData.append('chunk', (this.state.currentTrunk+1));
        formData.append('chunkSize', this.state.chunkSize);
        let config = {
            headers: {
                'Content-Type': 'multipart/form-data',
            }
        };
        service.post("/admin/react/upload/file",formData,config).then( response =>{
            if (response.data.code === 200 || response.data.code === 2222 || response.data.code === 1111){
                //处理存在分片的情况
                if (response.data.code === 1111){
                    console.log("已经存在分片");
                    console.log(response.data);
                    this.setState({
                        currentTrunk:response.data.index-1,
                        percent:((response.data.index-1) * 100) / this.state.data.chunkNum
                    },function () {
                        this.sendFile();
                    });
                }else { //正常情况
                    if (this.state.currentTrunk+1 === this.state.data.chunkNum){
                        this.uploadSuccess(response.data);
                        console.log("上传完成:",response.data)
                    }else {
                        this.setState({
                            currentTrunk:this.state.currentTrunk+1,
                            percent:((this.state.currentTrunk+1) * 100) / this.state.data.chunkNum
                        },function () {
                            this.sendFile();
                        });
                    }
                }
            }else {
                this.uploadError();
            }
        }).catch(error => {
            this.uploadError();
        })
    };

    canvasRef = useRef(null);

    handleClear = () => {
        const canvas = this.canvasRef.current;
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    };



    handleSaveAndUpload = () => {
        const canvas = this.canvasRef.current;
        const dataURL = canvas.toDataURL('image/png');

        axios.post('your_upload_endpoint', { image: dataURL })
            .then(response => {
                console.log('Image uploaded successfully:', response.data);
                alert('Image uploaded successfully!');
            })
            .catch(error => {
                console.error('Error uploading image:', error);
                alert('Image upload failed.');
            });
    };


    render() {
        const {getFieldDecorator} = this.props.form;
        const {label,field,initialValue,rules,disabled} = this.props;
        const new_props = diffProps(this.props,["form","label","field","initialValue","rules"]);
        return (
            <Form.Item label={label ? label : "手写签名"} disabled={disabled} {...new_props}>
                {getFieldDecorator(field ? field : "default_upload_file", {initialValue: initialValue,rules: rules ? rules : []})(
                    <Fragment>
                        <Progress style={{display:this.state.is_show_process ? "block" : "none"}} percent={parseInt(this.state.percent)} />
                        <Modal  visible={this.state.previewVisible} footer={null} onCancel={this.handleCancel}>
                            <canvas ref={this.canvasRef} width={400} height={200} style={{ border: '1px solid #000' }}></canvas>
                            <Button onClick={this.handleClear}>Clear</Button>
                            <Button onClick={this.handleSaveAndUpload}>Save and Upload</Button>
                        </Modal>
                    </Fragment>
                )}
            </Form.Item>
        );
    }
}